<template>
	<el-card>
		<div style="width: 800px">
			<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="220px">
				<el-form-item :label="$t('push.title')" prop="title">
					<el-input v-model="dataForm.title" :placeholder="$t('Enter')" maxlength="20" show-word-limit clearable></el-input>
				</el-form-item>
				<el-form-item :label="$t('push.content')" prop="content">
					<el-input
						v-model="dataForm.content"
						:placeholder="$t('Enter')"
						type="textarea"
						:rows="3"
						maxlength="50"
						show-word-limit
						clearable
					></el-input>
				</el-form-item>
				<!-- <el-form-item :label="$t('push.payload')" prop="payload">
					<el-input v-model="dataForm.payload" :placeholder="$t('Enter')" maxlength="50" show-word-limit clearable></el-input>
				</el-form-item> -->
				<!-- <el-form-item :label="$t('push.push_system')" prop="push_system" style="margin-bottom: 18px">
					<div class="w100">
						<el-select v-model="dataForm.push_system" value-key="" :placeholder="$t('PleaseSelect')" filterable clearable style="width: 100%">
							<el-option v-for="item in appType" :key="item.value" :label="$t(item.label)" :value="item.label" />
						</el-select>
					</div>
				</el-form-item> -->
				<!-- <el-form-item :label="$t('push.push_clientids')" prop="push_clientids">
					<el-input v-model="dataForm.push_clientids" :placeholder="$t('Enter')" maxlength="50" show-word-limit clearable></el-input>
				</el-form-item> -->
                <el-form-item :label="$t('push.push_clientids')" prop="type">
                    <div class="w100">
                        <el-select v-model="dataForm.type" value-key="" :placeholder="$t('PleaseSelect')" style="width:100%;" @change="select1">
                            <el-option :label="$t('push.alluser')" value="all" />
                            <el-option :label="$t('push.iosuser')" value="ios" />
                            <el-option :label="$t('push.anduser')" value="android" />
                            <el-option :label="$t('push.setuser')" value="set" />
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item :label="$t('push.userlist')" prop="push_clientids" v-if="dataForm.type == 'set'">
                    <div class="w100">
                        <el-select v-model="dataForm.push_clientids" value-key="" :placeholder="$t('PleaseSelect')" filterable multiple clearable style="width:100%;">
                            <el-option v-for="item in selectData1" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </div>
                </el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitHandle()" :loading="btnloading">{{ $t('push.add') }}</el-button>
					<!-- <el-button @click="visible = false">{{ $t('cancel') }}</el-button> -->
				</el-form-item>
			</el-form>
		</div>
	</el-card>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { postApi, postApiPush } from '@/api/api'
import { useI18n } from 'vue-i18n'
import { appType } from '@/config/youfu'
import { useRouter } from 'vue-router'
const router = useRouter()
const { t } = useI18n()
const visible = ref(false)
const btnloading = ref(false)
const dataFormRef = ref()
const oldDpId1 = ref('')
const oldDpId2 = ref('')
const oldDpId3 = ref('')
const selectData1 = ref([])
const dataForm = reactive({
	title: '',
	content: '',
	payload: '',
	push_system: '',
	type: 'all',
	push_clientids: ''
})
const dataRules = ref({
	title: [{ required: true, message: t('required'), trigger: 'change' }],
	content: [{ required: true, message: t('required'), trigger: 'change' }],
	payload: [{ required: true, message: t('required'), trigger: 'change' }],
	push_system: [{ required: true, message: t('required'), trigger: 'change' }],
	type: [{ required: true, message: t('required'), trigger: 'change' }],
	push_clientids: [{ required: true, message: t('required'), trigger: 'change' }]
})
const randomString = (len: any) => {
	let lens = len || 16
	let chars = '023456789abcdeoxn023456789'
	let maxPos = chars.length
	let pwd = ''
	for (let i = 0; i < lens; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos))
	}
	return pwd
}
const getSelectData = () => {
    postApi('/api/platform/user/list/all', {is_vip: 0}).then((result) => {
        // console.log(result.data);
        const hasData = result.data.filter(i => i.push_clientid);
        selectData1.value = hasData.map(item => {
            let label = item.name;
            if (item.email && label) {
                label += `（${item.push_system}）`;
            }else if (item.phone && label) {
                label += `（${item.push_system}）`;
            }else{
                label = item.email || item.phone;
            }
            return {
                push_system: item.push_system,
                value: item.push_clientid,
                label: label,
            }
        })
    }).catch((err) => {
        
    });
}
// 表单提交
const submitHandle = () => {
    if (!selectData1.value?.length) {
        ElMessage.warning({
            message: t('push.nouser'),
            duration: 1200
        })
        return;
    }
	dataFormRef.value.validate(async (valid: boolean) => {
		console.log(valid)
		if (!valid) {
			return false
		}
		let data: any = JSON.parse(JSON.stringify(dataForm));
        if (data.type == 'all') {
            data.push_clientids = selectData1.value.map(i=>i.value);
        }
        if (data.type == 'ios') {
            data.push_clientids = selectData1.value.filter(i=>i.push_system=='ios')?.map(i=>i.value);
        }
        if (data.type == 'android') {
            data.push_clientids = selectData1.value.filter(i=>i.push_system=='android')?.map(i=>i.value);
        }
		data.request_id = randomString(16);
		ElMessageBox.confirm(t('push.sub'), t('prompt'), {
			confirmButtonText: t('confirm'),
			cancelButtonText: t('cancel'),
			type: 'warning'
		})
			.then(async () => {
                // let platform: any = 'ALL';
                // const item = appType.find(i => i.label == data.push_system);
                // if(item){
                //     platform = [item.channel];
                // }
                const pushData = {
                    cids: data.push_clientids,
                    title: data.title,
                    content: data.content,
                    // data: {
                    //     text: '请进app查看',
                    //     page: '/index'
                    // },
                    badge: 0,
                    options: {
                        android: {
                            "XM": {
                                "/extra.channel_id": "129625" // 小米消息推送渠道ID
                            },
                            "XMG": {
                                "/extra.channel_id": "129625" // 小米消息推送渠道ID
                            }
                        }
                    },
                    force_notification: false, // 无论是离线推送还是在线推送，都自创建通知栏消息。HBuilderX 3.5.2 及其以上版本的客户端支持
                    request_id: data.request_id,
                    // platform: platform
                }
                console.log(pushData);
                if (pushData.cids.length) {
                    const pushRes = await postApiPush('/lulemepush', pushData, '');
                    if (pushRes.errCode == 0) {
                        data.push_result = 'push.success';
                    } else {
                        data.push_result = 'push.fail';
                    }
                } else {
                    data.push_result = 'push.success';
                }
                const nameList = selectData1.value.filter(i=>data.push_clientids.includes(i.value));
                data.push_names = nameList.map(i=>i.label).join(',');
                data.push_clientids = data.push_clientids.join(',');
                console.log(data);
				btnloading.value = true;
				postApi('/api/push/store', data, t('loading'))
					.then((res: any) => {
						if (res.code == 200) {
							ElMessage.success({
								message: t('opaSuccess'),
								duration: 500,
								onClose: () => {
									router.push({ path: '/push/logs' })
								}
							})
						} else {
							btnloading.value = false
							ElMessage.error({
								message: res.message || t('opaError'),
								duration: 1200
							})
						}
					})
					.catch(() => {
						btnloading.value = false
					})
			})
			.catch(() => {})
	})
}
const select1 = () => {
    nextTick(() => {
        setTimeout(() => {
            if(dataForm.type!='all'){
                dataFormRef.value.clearValidate('push_clientids');
            }
        }, 50);
    })
}
onMounted(() => {
    getSelectData();
})
</script>
